//
//  SC_Search_Table_VM.swift
//  APSwift
//
//  Created by jianbo.pei on 2023/4/26.
//

import UIKit

class SC_Search_Table_VM: VMBaseTableVM {

    public weak var tableView: UITableView?
    private var sectionModels: [SC_Search_Section_M] = []
    
    override init() {
        super.init()
        config.isMultipleSection = true
        config.headerClass = SC_Search_SectionHeaderView.self
    }
    
    public func loadData() {
        let result = jsonDict(forResource: "search_ep_page_1")
        guard let items = SC_Search_ResultModel.deserialize(from: result)?.items, !items.isEmpty else { return }
        handleResultDatas(items)
    }
    
    private func handleResultDatas(_ items: [SC_Search_ResultItemModel]) {
        for item in items {
            guard let type = item.type else { return }
            guard let itemInfoModel = item.itemInfoModel() else { return }

            /// 说明sectionModel已经存在
            if var section_M = sectionModels.first(where: { sm in
                if let smType = sm.type, smType == type {
                    return true
                } else {
                    return false
                }
            }) {
                section_M.type = type
                setupDatas(of: &section_M, type: type, itemInfoModel: itemInfoModel)
            }
            
            /// 说明sectionModel不存在，需要新建
            else {
                var section_M = SC_Search_Section_M()
                setupDatas(of: &section_M, type: type, itemInfoModel: itemInfoModel)
                
                /// 设置header
                var header_M = SC_Search_Header_M()
                header_M.title = type.cnName
                section_M.headerModel = header_M
                
                sectionModels.append(section_M)
            }
        }
        datasOfSection = sectionModels
        tableView?.reloadData()
    }
    
    private func setupDatas(of section_M: inout SC_Search_Section_M, type: SC_Search_ResultItemModel.SearchType, itemInfoModel: APReuseView_M_Protocol) {
        section_M.type = type
        if section_M.datas != nil {
            section_M.datas?.append(itemInfoModel)
        } else {
            var datas: [Any] = []
            datas.append(itemInfoModel)
            section_M.datas = datas
        }
    }
    
}
